<?php
namespace Erp\C\Orders\Tn\Shipping;
use Erp\C\Orders\Tn\Shipping\Shipping;
use Erp\C\Orders\Tn\Api\ApiIspModule;
use Fn;
//万邑通eBay线上中邮小包平邮
class Isp extends Shipping
{
    private $api_isp;
    private $ordersRes = array();
    function __construct()
    {
        $this->api_isp =new ApiIspModule();
    }
    /**
     *获取TN入口方法
     *@param array $Orders array(1,2,3) || string 2
     */
    public function getTn($Orders){
        if (!is_array($Orders)) {
            $Orders = array($Orders);
        }
        $count = count($Orders);
        $multi_num = 5;
        $for_num = ceil($count/$multi_num);
        for ($i=0; $i < $for_num; $i++) {
            $s = $i*$multi_num;
            $tmp_arr = array_slice($Orders,$s,$multi_num);
            $this->ispApiMgr($tmp_arr);
        }
    }
        /**
         *获取地万邑通TN流程
         *@param array $tmp_arr 数组 订单号
         */
        public function ispApiMgr($tmp_arr){
            $request_data = $this->createPackageParams($tmp_arr);   //生成请求数据
            Fn\App::log('kim_dsf',$request_data,"DSF获取TN数据");
            $response = $this->api_isp->createAndConfirmPackages($request_data);  //api提交数据
            Fn\App::log('kim_dsf',$response,"DSF获取TN数据");
//            var_dump($response);die();
            $this->disposePackageReturn($response);
        }
        /**
         * 拼接数据
         *创建线上包裹数据格式
         *@param array $tmp_arr
         *@return array
         */
        public function createPackageParams($tmp_arr){
            $o_model = A('Orders');
            $multi_request = array();
            foreach ($tmp_arr as $k => $ordersId) {
                $action = 'isp.order.createOrder'; //action
                $orderInfo = $o_model->combinOrderInfo($ordersId);//获取订单信息
//                $platform = $orderInfo['orders_platform'];
                $platform = 'SELLERERP';
                $shipping = $orderInfo['orders_shipping_method'];
                $shippingArr = $this->_shippingEnumerate($shipping); // 运输方式转换 :ERP代码 ---->
                $productList = $orderInfo['orders_items'];
                $count = '';
                $price = '';
                foreach ($productList as  $orderProduct) {
                    $count += $orderProduct['orders_product_quantity'];
                    $price += $orderProduct['orders_item_total_price_usd'];
                }
                $unitPrice = $price/$count;
                $unitPrice = round($unitPrice,2);
                //商品列表,以下字段为merchandiseList子节点
                $merchandiseList = array();
                foreach ($productList as $key=>$orderProduct){
                    $productId = $orderProduct['product_id'];
                    $CustomsInfo = $this->getRealCustomsName($productId);	//报关名
                    $categoryCnDesc = $CustomsInfo['ClassnameForCustomsCn'];//报关中文名
                    $categoryEnDesc = $CustomsInfo['ClassnameForCustoms'];//报关英文名
                    $merchandiseList[$key]=array(
                        "declaredNameCn"	=> $categoryCnDesc, //申报品名(中文)
                        "declaredNameEn"	=> $categoryEnDesc,//申报品名（英文）
                        "declaredValue"		=> $unitPrice,//单个商品申报价格(USD)
                        "itemID"			=> $orderProduct['item_id'],//	条目ID（eBay订单必填）
                        "transactionID"		=> $orderProduct['orders_item_id'],//交易ID（eBay订单必填）
                    );
                    break;
                }
                $data = array(
                    'buyerAddress1'		=> $orderInfo['orders_delivery_address'],//收件人地址1
                    'buyerAddress2'		=> $orderInfo['orders_delivery_address2'],//收件人地址2
                    'buyerCity'			=> $orderInfo['orders_delivery_city'],//收件人城市
                    'buyerContactNo'	=> $orderInfo['orders_delivery_tel'],//收件人电话
                    'buyerCountry'		=> $orderInfo['orders_delivery_country_iso'],//收件人国家
                    'buyerEmail'        =>$orderInfo['orders_customer_email'], //收件人邮箱
                    'buyerName'			=> $orderInfo['orders_delivery_name'],//收件人名字
                    'buyerState'		=> $orderInfo['orders_delivery_state'],//收件人州
                    'buyerZipCode'		=> $orderInfo['orders_delivery_postcode'],//收件人邮编
                    'dispatchType'		=> 'P',//发货方式
                    'ebaySellerId'		=> $orderInfo['orders_shop_name'], //卖家id
                    'packageList'		=> array(//包裹列表,以下字段为packageList子节点
                        array(
                            'height'	=> 10,//高 cm
                            'length'	=> 15,//长 cm
                            'merchandiseList'=> $merchandiseList,
                            'weight'	=> $orderInfo['orders_weight'],//重量（KG）
                            'width'		=> 10,//宽 cm
                        )),
                    "refNo" => $ordersId,//erp订单号
                    'shipperAddrCode'	=> $shippingArr['shipperAddrCode'],//寄件人地址code
                    'warehouseCode'		=> $shippingArr['warehouseCode'],// 仓库Code，必须填写,取【寄件人地址code】审核的的验货仓库
                    'winitProductCode'	=> $shippingArr['winitProductCode'],//winit产品编码，即物流产品代码
                );

                $res = $this->_getSignAndData($action,$data,$platform);
                $multi_request[$ordersId] = array('post'=>$res,'header'=>$this->api_isp->header,'url'=>$this->api_isp->url);
                unset($res);unset($arr);
            }
            return $multi_request;
        }

    //ERP运输方式转换成API标准的运输方式
    private function _shippingEnumerate($name){
        switch($name){
            case 'EDS':
                return array('shipCode'=>'WP-HKP101','shipperAddrCode'=>'523000','warehouseCode'=>'YW10000008','header'=>$this->api_isp->header);
            case 'EBAYCNPY':
                return array('shipperAddrCode'=>'523000','warehouseCode'=>'YW10000008','winitProductCode'=>'WP-CNP007','header'=>$this->api_isp->header);
            default:
                return false;
        }
    }

    //获取组装参数（线上包裹和面单）
    private function _getSignAndData($action,$data,$platform){
        $time = date('Y-m-d H:i:s');
        $jsonData = json_encode($data);
        $sign= "{$this->api_isp->token}action{$action}app_key{$this->api_isp->app_key}data{$jsonData}format{$this->api_isp->format}platform{$platform}sign_method{$this->api_isp->sign_method}timestamp{$time}version{$this->api_isp->version}{$this->api_isp->token}";
        $sign = strtoupper(md5($sign));
        $arr = array(
            'action'=>$action,
            'app_key'=>$this->api_isp->app_key,
            'data'	=>$data,
            'format'=>$this->api_isp->format,
            'platform'=>$platform,
            'sign'=>$sign,
            'sign_method'=>$this->api_isp->sign_method,
            'timestamp'=>$time,
            'version'=>$this->api_isp->version
        );
        $res = json_encode($arr);
        return $res;
    }

    /**
     *获取lable入口
     *@param array $Orders 一维数组
     */
    public function getLable($Orders){
        $this->_getPdf($Orders);
    }
    /**
     *获取tn成功后调用此方法获取面单Pdf
     *@param array $Orders 一维数组订单号
     */
    private function _getPdf($Orders){
        if(!$Orders){
            echo "无订单".__LINE__;
        }
        $this->_requestLable($Orders);
    }

    /**
     *处理提交包裹所返回的响应
     *@param array $multi_request_res
     *	1:"待取TN",
     *	6:"TN失败",
     *	7:"已取TN",
     *	8:"PDF失败"
     *	99: 成功
     */
    public function disposePackageReturn($multi_request_res){
        if ($multi_request_res) {
            foreach ($multi_request_res as $k => $v) {
                if (!is_array($v)) {
                    $v = json_decode($v,true);
                }
                $ordersStatus = A('Orders')->getOrdersStatus($k);
                if ($v['code']==0 && isset($v['code'])) {
                    $ordersData = array();
                    $ordersData['orders_tn'] = $v['data']['trackingNo'];
                    if(!$ordersData['orders_tn']) continue;
                    if ($ordersStatus == '300') {
                        $ordersData['orders_status_children'] == 7;
                    }
                    A('Orders')->saveData($ordersData,$k);
                    $ordersShippingExtendArr = $v['data']['orderNo'];
                    $info = A('orders_shipping_extend')->getExtendValue($k);
                    if($info){
                        //修改扩展数据
                        A('orders_shipping_extend')->saveExtendValue($k,$ordersShippingExtendArr);
                    }else{
                        //新增扩展数据
                        A('orders_shipping_extend')->addExtendValue($k,$ordersShippingExtendArr);
                    }
                    A('Orders')->saveOrderHistory($k,'获取万邑通eBay线上中邮小包平邮TN成功--',$ordersData);
                }else{
                    $ordersData = array();
                    if ($v['code'] != 0) {
                        $errorsMsgs = $v['msg'];
                        if ($ordersStatus == '300') {
                            $ordersData['orders_status_children'] = 6;
                            A('Orders')->saveData($ordersData);
                        }
                        A('Orders')->saveOrderHistory($k,"获取万邑通eBay线上中邮小包平邮TN失败:".$errorsMsgs);
                    }
                }
            }
        }
    }

    /**
     * @param $orders
     * 拼接label面单参数
     */
    private function _requestLable($orders){
        $oModel=A('Orders');
        $res = $oModel->getOrders($orders);
        $root_dir = "./Public/Data/Files/";
        if ($res) {
            foreach ($res as $k => $v) {
                $ordersId = $v['orders_id'];
                $time = $v['orders_import_time'];
                $dir_local_root = $root_dir.date('Ymd',$time)."/";
                $filename = $ordersId.'.pdf';
                //删除PDF
                if(file_exists($dir_local_root.$filename)){
                    @unlink($dir_local_root.$filename);
                }
                $action = 'winitLable.query';
                $ordersShipData = A('orders_shipping_extend')->getExtendValue($ordersId);
                $data = array();
                $data['orderNo'] = $ordersShipData['extend_value'];
//                $platform 	= $v['orders_platform'];
                $platform 	= 'SELLERERP';
                $jsonData 	= $this->_getSignAndData($action,$data,$platform);
                $response 	= $this->api_isp->createPackageLable($jsonData);
                $response 	= json_decode($response,true);
                $content	= $response['data']['files'][0];
                $content 	= base64_decode($content);
                $is_exists = $this->saveShippingLable($dir_local_root,$filename,$content);
                Fn\App::log('isp_Dff_error',array(
                    'response'=>$response,
                    'isExists'=>$is_exists,
                    'url'=>$dir_local_root.$filename
                ),"万邑通eBay线上中邮小包平邮请求PDF调试");
                if(!$is_exists){
                    sleep(2);
                    $response = $this->api_isp->createPackageLable($jsonData);
                    $response = json_decode($response,true);
                    $content  = $response['data']['files'][0];
                    $content  = base64_decode($content);
                    $is_exists = $this->saveShippingLable($dir_local_root,$filename,$content);
                }
                if($is_exists){
                    $saveData = array();
                    $saveData['orders_pdf_exist'] = 1;
                    $ordersStatus = $v["orders_status"];
                    if($ordersStatus == '300'){
                        $saveData['orders_status_children'] = 99;
                    }
                    A('Orders')->saveData($saveData,$ordersId);
                    A('Orders')->saveOrderHistory($ordersId,'获取万邑通eBay线上中邮小包平邮PDF成功');
                }else{
                    $saveData = array();
                    $ordersStatus = $v['orders_status'];
                    if($ordersStatus == '300'){
                        $saveData['orders_status_children'] = 8;
                    }
                    A('Orders')->saveData($saveData);
                    A('Orders')->saveOrderHistory($ordersId,'获取万邑通eBay线上中邮小包平邮PDF失败');
                }
            }
        }
    }

}